<template>
	<view class="container">
		<view class="panel-header padding-top solid-bottom">
			<view class="g-goBack" @click="$utils.toBack()">
				<view class="cuIcon-back"></view>
			</view>
			<view class="text-cut">分成配置({{placeName}})</view>
		</view>
		<scroll-view scroll-x="true" class="bg-white nav" v-if="businessTypeList && businessTypeList.length > 1">
			<view class="flex text-center">
				<view class="cu-item flex-sub" :class="index == typeSelectIndex?'text-orange cur':''"
					v-for="(item,index) in businessTypeList" :key="index" @click="bindTypeChange(index)">
				{{item.businessTypeName}}
				</view>
			</view>
		</scroll-view>
		<view class="list-body">
			<scroll-view scroll-y="true">
				<block v-if="typeSelectIndex > 0">
					<view class="cu-bar bg-white solid-bottom margin-top">
						<view class="action">
						  <text class="cuIcon-title text-orange "></text> 列表左滑操作
						</view>
						<view class="action">{{businessTypeList[typeSelectIndex].businessTypeName}}</view>
					</view>
					<view class="cu-list menu-avatar">
						<block v-for="(item,index) in typeProfitListData" :key="index">
							<view class="cu-item bg-grey" v-if="item.roleType == 1">
								<view class="cu-avatar round lg" style="background-image:url(/static/def_face.jpg);"></view>
								<view class="content">
									<view class="text-grey">{{item.userName}}</view>
									<view class="text-gray text-sm"><text class="cuIcon-tag text-red"></text>{{item.roleTypeName}}</view>
								</view>
								<view class="action">
									<view class="text-grey">{{item.incomeRatio}}%</view>
								</view>
							</view>
							<view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''" v-else
								@touchstart="ListTouchStart" @touchmove="ListTouchMove" @touchend="ListTouchEnd" :data-target="'move-box-' + index">
								<view class="cu-avatar round lg" style="background-image:url(/static/def_face.jpg);"></view>
								<view class="content">
									<view class="text-grey">{{item.userName}}</view>
									<view class="text-gray text-sm"><text class="cuIcon-tag text-red"></text>{{item.roleTypeName}}</view>
								</view>
								<view class="action">
									<view class="text-grey">{{item.incomeRatio}}%</view>
								</view>
								<view class="move">
									<view class="bg-red" @click="btnDel(item.userIndex)">删除</view>
									<view class="bg-grey" @click="btnUpdate(item.userIndex)">修改</view>
								</view>
							</view>
						</block>
					</view>
					<view class="foot" v-if="typeProfitListData && typeProfitListData.length > 0"><text class="ftxt">我也是有底线的</text></view>
					<view class="foot" v-else><text class="ftxt">暂无数据</text></view>
				</block>
				<block v-else>
					<view class="cu-card article" v-for="(item,index) in listData" :key="index">
						<view class="cu-item padding">
						   <view class="content margin-bottom">
							   <image :src="item.faceImg?item.faceImg:'/static/def_face.jpg'" mode="aspectFit"></image>
							   <view class="text-cut">
								   <view class="text-cut text-orange">姓名：{{item.userName}}</view>
								   <view>角色：{{item.roleTypeName}}</view>
								   <view>手机号：{{item.userPhone}}</view>
								   <view>备注：{{item.note || '---'}}</view>
								   <view>加入时间：{{item.createDate}}</view>
							   </view>
						   </view>
						   <view class="profit-info margin" v-if="businessTypeList && businessTypeList.length > 1">
							   <view class="flex justify-between solid-bottom padding-bottom-sm" v-for="(profit,profitIndex) in item.incomeRatioItems">
									<view>{{profit.businessTypeName}}</view>
									<view>{{profit.incomeRatio}}%</view>
							   </view>
						   </view>
						   <view class="flex justify-end" v-if="item.roleType != 1">
							   <button class="cu-btn round line-red margin-bottom-sm margin-right-sm sm" @click="btnDel(index)">删除</button>
							   <button class="cu-btn round line-grey margin-bottom-sm margin-right-sm sm" @click="btnUpdate(index)">修改</button>
						   </view>
					   </view>
					</view>
					<view class="foot" v-if="listData && listData.length > 0"><text class="ftxt">我也是有底线的</text></view>
					<view class="foot" v-else><text class="ftxt">暂无数据</text></view>
				</block>
		    </scroll-view>
		</view>
		<view class="cu-bar btn-group list-footer">
		    <button class="cu-btn bg-orange shadow-blur round" @click="btnAdd()">新增分成用户</button>
		</view>
		
		<view class="cu-modal" :class="modalName=='editModal'?'show':''">
			<view class="cu-dialog bg-white">
				<view class="cu-bar bg-white justify-end">
					<view class="content">编辑分成用户</view>
					<view class="action" @click="btnHideModal()">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<block v-if="editStep == 1">
					<form>
						<view class="cu-form-group">
							<view class="title">手机号</view>
							<input placeholder="请填写(必填项)" v-model="info.phone"></input>
						</view>
					</form>
					<view class="cu-bar btn-group margin-top">
						<button class="cu-btn bg-grey shadow-blur round" @click="btnHideModal()">取消</button>
						<button class="cu-btn bg-orange shadow-blur round" @click="btnFindUser()">查询用户</button>
					</view>
				</block>
				<block v-else>
					<form>
					    <view class="cu-form-group">
							<view class="title">手机号</view>
							<view>{{info.phone}}</view>
					    </view>
						<view class="cu-form-group" v-if="editUserName">
							<view class="title">姓名</view>
							<input placeholder="请填写(必填项)" v-model="info.name"></input>
						</view>
						<view class="cu-form-group" v-else>
							<view class="title">姓名</view>
							<view>{{info.name}}</view>
						</view>
						<view class="cu-form-group">
							<radio-group class="grid col-2 role-info" @change="bindRoleTypeChange">
								<view><radio class="blue" value="2" :checked="info.roleType==2"></radio><text>商户</text></view>
								<view><radio class="blue" value="3" :checked="info.roleType==3"></radio><text>合伙人</text></view>
							</radio-group>
						</view>
						<view class="cu-form-group">
							<view class="title">备注</view>
							<input placeholder="请填写(非必填)" v-model="info.note"></input>
						</view>
						<block v-for="(item,index) in businessTypeList" :key="index">
							<view class="cu-form-group" v-if="index > 0">
								<view class="title">{{item.businessTypeName}}</view>
								<input placeholder="请填写分成比例" v-model="info.incomeRatioMap[item.businessType]"></input>
								<text>%</text>
							</view>
						</block>
					</form>
					<view class="cu-bar btn-group margin-top">
					    <button class="cu-btn bg-grey shadow-blur round" @click="btnHideModal()">取消</button>
						<button class="cu-btn bg-orange shadow-blur round" @click="btnSaveSubmit()">确定</button>
					</view>
				</block>
			</view>
		</view>
		<view class="cu-modal error-modal" :class="errorModal?'show':''">
			<view class="cu-dialog padding text-red">
				<view class="padding">{{errorMsg}}</view>
				<view class="flex margin-top solids-top">
					<button class="cu-btn bg-btn-text flex-sub" @click="bindHideErrorModal()">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				placeId:null,
				placeName:'网点名称',
				businessTypeList:[{businessType:'0',businessTypeName:'全部'}],
				typeSelectIndex:0,
				
				listData:[],
				typeProfitListData:[],			//业务类型分成
				
				roleTypeList:['商户'],
				
				info:{
					incomeRatioMap:{}
				},
				editStep:1,				//编辑用户的步数，1:查询用户，2:编辑用户
				editUserName:true,		//是否可以编辑用户名称
				
				errorMsg:'',
				errorModal:false,
				
				modalName: null,
				listTouchStart: 0,
				listTouchDirection: null
			}
		},
		onLoad(option) {
			const _self = this;
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('fromData', function(data) {
			    console.log(data)
				_self.placeId = data.placeId;
				_self.placeName = data.placeName;
				_self._loadBusinessType();
				_self._loadDataList();
			})
		},
		methods: {
			_loadDataList:function(){
				if(this.placeId){
					uni.showLoading({
						title:'处理中...'
					})
					const _self = this;
					const api = this.$request;
					api.post(api.url.placeUserList,{
						placeId:this.placeId
					},res=>{
						uni.hideLoading();
						console.log(res);
						if(res.code==200){
							_self.listData = res.body.userItems||[];
							if(_self.typeSelectIndex > 0){
								_self.bindTypeChange(_self.typeSelectIndex);
							}
						}else if(res.msg){
							uni.showModal({
								content:res.msg,
								showCancel:false,
								complete:function(){
									uni.navigateBack();
								}
							});
						}else {
							uni.showToast({
								title:'获取数据失败',
								icon:'error'
							});
							setTimeout(function(){
								uni.navigateBack();
							},1000);
						}
					})
				}else{
					uni.showToast({
						title:'参数错误',
						icon:'error'
					});
					setTimeout(function(){
						uni.navigateBack();
					},1000);
				}
			},
			_loadBusinessType:function(){
				const api = this.$request;
				api.post(api.url.placeBusiTypeList,{
					placeId:this.placeId
				},res=>{
					console.log(res);
					if(res.code==200){
						let businessTypeList = [{businessType:'0',businessTypeName:'全部'}]
						for(let i in res.body.items){
							businessTypeList.push(res.body.items[i]);
						}
						this.businessTypeList = businessTypeList;
					}else if(res.code==202){
						//不做任何事
					}else if(res.msg){
						uni.showModal({
							content:res.msg,
							showCancel:false
						})
					}else {
						uni.showToast({
							title:'获取数据失败',
							icon:'error'
						});
					}
				})
			},
			bindTypeChange:function(index){
				this.typeSelectIndex = index;
				if(this.typeSelectIndex > 0){
					let type = this.businessTypeList[this.typeSelectIndex];
					let typeProfitListData = [];
					for(let i in this.listData){
						let user = this.listData[i];
						if(user.incomeRatioItems && user.incomeRatioItems.length > 0){
							for(let j in user.incomeRatioItems){
								let profit = user.incomeRatioItems[j];
								if(profit.businessType == type.businessType){
									typeProfitListData.push({
										userId:user.userId,
										userName:user.userName,
										roleType:user.roleType,
										roleTypeName:user.roleTypeName,
										incomeRatio:profit.incomeRatio,
										userIndex:i
									})
									break;
								}
							}
						}
					}
					if(typeProfitListData.length == 0){
						for(let i in this.listData){
							let user = this.listData[i];
							if(user.roleType == 1){
								typeProfitListData.push({
									userId:user.userId,
									userName:user.userName,
									roleType:user.roleType,
									roleTypeName:user.roleTypeName,
									incomeRatio:100,
									userIndex:i
								})
								break;
							}
						}
					}
					this.typeProfitListData = typeProfitListData;
				}
			},
			
			bindRoleTypeChange:function(e){
				this.info.roleType = e.detail.value;
			},
			
			bindHideErrorModal:function(){
				this.errorMsg = '';
				this.errorModal = false;
			},
			
			btnHideModal:function(){
				this.modalName = null;
			},
			
			btnAdd:function(){
				this.editStep = 1;
				this.info = {
					roleType:2,
					incomeRatioMap:{}
				}
				this.modalName = 'editModal';
			},
			
			btnUpdate:function(index){
				let user = this.listData[index];
				if(user){
					let incomeRatioMap = {};
					for(let i in user.incomeRatioItems){
						let item = user.incomeRatioItems[i];
						incomeRatioMap[item.businessType] = item.incomeRatio;
					}
					let info = {
						userId:user.userId,
						phone:user.userPhone,
						name:user.userName,
						note:user.note,
						roleType:user.roleType,
						incomeRatioMap:incomeRatioMap
					}
					this.info = info;
					this.editStep = 2;
					this.editUserName = false;
					this.modalName = 'editModal';
				}
			},
			
			btnDel:function(index){
				let user = this.listData[index];
				if(user){
					const api = this.$request;
					const _self = this;
					uni.showModal({
						title:'温馨提示',
						content:'确定要删除【' + user.userName + '】用户吗？',
						complete:function(res){
							if(res.confirm){
								api.post(api.url.placeUserDel,{
									placeId:_self.placeId,
									userId:user.userId
								},res=>{
									console.log(res);
									if(res.code==200){
										_self._loadDataList();
									}else if(res.msg){
										uni.showModal({
											content:res.msg,
											showCancel:false
										})
									}else {
										uni.showToast({
											title:'操作失败',
											icon:'error'
										});
									}
								})
							}
						}
					})
				}
			},
			
			//根据手机号查询用户
			btnFindUser:function(){
				console.log(this.info.phone);
				if(!this.info.phone){
					this.errorMsg = '请填写手机号';
					this.errorModal = true;
					return;
				}
				
				const api = this.$request;
				api.post(api.url.commUserFind,{
					phone:this.info.phone
				},res=>{
					console.log(res);
					if(res.code==200){
						this.editUserName = false;
						this.info.name = res.body.nickname;
						this.editStep = 2;
					}else{
						this.editUserName = true;
						this.editStep = 2;
					}
				})
			},
			
			btnSaveSubmit:function(){
				let info = this.info;
				info.placeId = this.placeId;
				const _self = this;
				const api = this.$request;
				api.post(api.url.placeUserSave,info,res=>{
					console.log(res);
					if(res.code==200){
						this.modalName = null;
						uni.showToast({
							title:'保存成功',
							icon:'success'
						})
						setTimeout(function(){
							_self._loadDataList();
						},1000)
					}else if(res.msg){
						this.errorMsg = res.msg;
						this.errorModal = true;
					}else {
						this.errorMsg = '保存失败';
						this.errorModal = true;
					}
				})
			},
			
			// ListTouch触摸开始
			ListTouchStart(e) {
				this.listTouchStart = e.touches[0].pageX
			},
			
			// ListTouch计算方向
			ListTouchMove(e) {
				this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
			},
			
			// ListTouch计算滚动
			ListTouchEnd(e) {
				if (this.listTouchDirection == 'left') {
					this.modalName = e.currentTarget.dataset.target
				} else {
					this.modalName = null
				}
				this.listTouchDirection = null
			}
		}
	}
</script>

<style lang="less">
.container .list-body scroll-view{height:86vh;}
.container .list-body .cu-card.article>.cu-item .content>uni-image{width:160rpx;}
.container .list-body .cu-card.article>.cu-item{margin-bottom:0;padding-bottom:0;font-size:26rpx;}
.container .list-footer{position: fixed;bottom: 0;left:0;right:0;}
.container .cu-form-group{text-align:right;}
.container .cu-form-group .title {min-width: calc(4em + 30rpx);}
.container .cu-form-group .role-info{width:100%;text-align:center;}
.container .cu-form-group .role-info text{padding-left:5rpx;}
.cu-list.menu-avatar>.cu-item.bg-grey{background-color: #eee;}
</style>
